//
//  LXVideoShowViewController.m
//  cat
//
//  Created by imera on 16/3/8.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "LXVideoShowViewController.h"
#import "MoviePlayerViewController.h"
#import "UIImage+Lx.h"
#import "LXCostumButton.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "MBProgressHUD+MJ.h"
#import "LXSearchTableViewCell.h"
#import "LXVideoShowViewController.h"
#import "LXImageOnTopButton.h"
#import "LXLoginViewController.h"
#import "LXConcernUserInfoCell.h"

#define LXVideoShowViewControllerTableViewHeaderHeight 180

@interface LXVideoShowViewController () <UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, LXConcernUserInfoCellDelegate>
/*** 顶部视图 */
@property (nonatomic, weak) UIView *topView;
/*** 底部视图 */
@property (nonatomic, weak) UIView *bottomView;
/*** 当前选择的btn */
@property (nonatomic, weak) UIButton *currentBtn;
/*** 当前选集 */
@property (nonatomic, weak) UIButton *currentVideoBtn;
/*** 滚动视图 */
@property (nonatomic, weak) UIScrollView *scrollView;
/*** 滚动指示器 */
@property (nonatomic, weak) UIScrollView *sliderView;
/***  切换按钮 */
@property (nonatomic, strong) NSMutableArray *tabBtnArr;
/***  简介图片 */
@property (nonatomic, weak) UIImageView *briefView;
/***  视频名称 */
@property (nonatomic, weak) UILabel *titleLabel;
/***  视频描述 */
@property (nonatomic, weak) UILabel *describeLabel;
/***  视频内容介绍 */
@property (nonatomic, weak) UILabel *detailLabel;
/***  推荐视频cell */
@property (nonatomic, weak) UITableView *recommendVideoTableView;
/***  推荐视频信息数组 */
@property (nonatomic, strong) NSArray *videoArr;

/***  收藏视频信息数组 */
@property (nonatomic, strong) NSArray *markVideoArr;
/** 收藏 */
@property (nonatomic, weak) UIButton *markButton;
/** 收藏数字 */
@property (nonatomic, weak) UILabel *markLabel;
/** 猫粮数字 */
@property (nonatomic, weak) UILabel *catFoodLabel;
/** 视频下载文件 */
@property (nonatomic, strong) NSMutableArray *videoDownLoad;
/** 视频缓存信息文件路径 */
@property (nonatomic, copy) NSString *filePath;
/** 视频历史记录 */
@property (nonatomic, copy) NSMutableArray *historyVideoArr;

@property (nonatomic, strong) NSArray *userArr;
@end

@implementation LXVideoShowViewController

- (NSString *)filePath
{
    if (_filePath == nil) {
        NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        _filePath = [docPath stringByAppendingPathComponent:@"downloadVideo.plist"];
    }
    return _filePath;
}

#pragma mark - 视频缓冲文件懒加载
- (NSArray *)videoDownLoad
{
    if (_videoDownLoad == nil) {
        _videoDownLoad = [NSMutableArray arrayWithContentsOfFile:self.filePath];
        if (_videoDownLoad == nil) {
            _videoDownLoad = [NSMutableArray array];
        }
    }
    return _videoDownLoad;
}

#pragma mark - 视频历史记录文件懒加载
- (NSArray *)historyVideoArr
{
    if (_historyVideoArr == nil) {
        NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *file = [docPath stringByAppendingPathComponent:@"history.plist"];
        _historyVideoArr = [NSMutableArray arrayWithContentsOfFile:file];
        if (_historyVideoArr == nil) {
            _historyVideoArr = [NSMutableArray array];
        }
    }
    return _historyVideoArr;
}

- (NSMutableArray *)tabBtnArr
{
    if (_tabBtnArr == nil) {
        _tabBtnArr = [NSMutableArray array];
    }
    return _tabBtnArr;
}

- (void)setVideo:(LXVideo *)video
{
    if (video != nil) {
        _video = video;
        
        [self getVideoInfo];
    }
}

#pragma mark - 获取视频信息
- (void)getVideoInfo
{
    //获取数据
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    NSString *url = @"http://cat666.com/cat666-interface/index.php/index/getVideoInfo";
    
    [mgr POST:url parameters:@{@"videoid":@(self.video.ID)} success:^(AFHTTPRequestOperation *operation, id response) {
        NSDictionary *dict = response;
        _user = [LXUser initWithDict:dict[@"user"]];
        _video = [LXVideo initWithDict:dict[@"video"]];
        
        //监听视频的播放量
//        [_video addObserver:self forKeyPath:@"viewcounts" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        [MBProgressHUD showError:@"您的网络开小差了..."];
    }];
}

//#pragma mark - 监听视频的播放量
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
//{
//    if ([keyPath isEqualToString:@"viewcounts"]) {
//        NSString *describe = [NSString stringWithFormat:@"已完结\n%ld次播放 %ld次评论",self.video.viewcounts,self.video.videocomments];
//        self.describeLabel.text = describe;
//    }
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initNavBar];
    
    [self initTopView];
    
    [self initBottomView];
    
    [self getRecommendVideos];
    
    [self getConcern];
}

#pragma mark - 获取关注列表
- (void)getConcern
{
    NSString *userName = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
    if (userName == nil) {
        self.userArr = [NSArray array];
        return;
    }
    //获取数据
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    
    NSString *url = @"http://cat666.com/cat666-interface/index.php/index/getFollow";
    
    [mgr POST:url parameters:@{@"userid":userId} success:^(AFHTTPRequestOperation *operation, id response) {
        NSArray *arr = response;
        if ([response isKindOfClass:[NSDictionary class]]) {
            self.userArr = [NSArray array];
            [self.recommendVideoTableView reloadData];
        }else{
            NSMutableArray *userArr = [NSMutableArray array];
            for (NSDictionary *dict in arr) {
                LXUser *user = [LXUser initWithDict:dict];
                [userArr addObject:user];
            }
            self.userArr = userArr;
            [self.recommendVideoTableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        [MBProgressHUD showError:@"您的网络开小差了..."];
    }];
}

#pragma mark 自定义导航条
- (void)initNavBar
{
    UIView *navBarView = [[UIView alloc]init];
    navBarView.backgroundColor = LXColor(41, 188, 208);
    navBarView.frame = CGRectMake(0, 20, self.view.frame.size.width, 40);
    [self.view addSubview:navBarView];
    
    LXCostumButton *backBtn = [LXCostumButton buttonWithType:UIButtonTypeCustom];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [backBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"arrow"] forState:UIControlStateNormal];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    CGFloat backBtnW = 60;
    CGFloat backBtnH = 30;
    CGFloat backBtnX = LXMovieShowViewControllerMargin;
    CGFloat backBtnY = (navBarView.frame.size.height - backBtnH) / 2;
    backBtn.frame = CGRectMake(backBtnX, backBtnY, backBtnW, backBtnH);
    [navBarView addSubview:backBtn];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 初始化顶部视图
- (void)initTopView
{
    UIView *topView = [[UIView alloc]init];
    topView.backgroundColor = [UIColor whiteColor];
    CGFloat topViewX = 0;
    CGFloat topViewY = 60;
    CGFloat topViewW = self.view.frame.size.width;
    CGFloat topViewH = 200;
    topView.frame = CGRectMake(topViewX, topViewY, topViewW, topViewH);
    [self.view addSubview:topView];
    self.topView = topView;
    
    UIImageView *imageView = [[UIImageView alloc]init];
    CGFloat imageViewX = LXMovieShowViewControllerMargin;
    CGFloat imageViewY = LXMovieShowViewControllerMargin;
    CGFloat imageViewW = self.view.frame.size.width * 0.4;
    CGFloat imageViewH = 110;
    imageView.frame = CGRectMake(imageViewX, imageViewY, imageViewW, imageViewH);
    [topView addSubview:imageView];
    
    self.briefView = imageView;
    [self.briefView sd_setImageWithURL:[NSURL URLWithString:self.video.thumb]];
    
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.font = [UIFont boldSystemFontOfSize:14];
    titleLabel.numberOfLines = 0;
    CGFloat titleLabelX = CGRectGetMaxX(imageView.frame) + LXMovieShowViewControllerMargin;
    CGFloat titleLabelY = imageViewY;
    CGFloat titleLabelW = topViewW - imageViewW - 3 * LXMovieShowViewControllerMargin;
    CGFloat titleLabelH = 35;
    titleLabel.frame = CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH);
    [topView addSubview:titleLabel];
    
    self.titleLabel = titleLabel;
    self.titleLabel.text = self.video.fname;
    
    UILabel *describeLabel = [[UILabel alloc]init];
    describeLabel.numberOfLines = 2;
    describeLabel.font = [UIFont systemFontOfSize:14];
    CGFloat describeLabelX = titleLabelX;
    CGFloat describeLabelY = CGRectGetMaxY(titleLabel.frame) + 0.2 * LXMovieShowViewControllerMargin;
    CGFloat describeLabelW = titleLabelW;
    CGFloat describeLabelH = 40;
    describeLabel.frame = CGRectMake(describeLabelX, describeLabelY, describeLabelW, describeLabelH);
    [topView addSubview:describeLabel];
    
    self.describeLabel = describeLabel;
    NSString *describe = [NSString stringWithFormat:@"已完结\n%ld次播放 %ld次评论",self.video.viewcounts,self.video.videocomments];
    self.describeLabel.text = describe;
    
    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    playBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    [playBtn setTitle:@"播放" forState:UIControlStateNormal];
    [playBtn setBackgroundImage:[UIImage resizeWithName:@"button-blue"] forState:UIControlStateNormal];
    [playBtn addTarget:self action:@selector(moviePlay) forControlEvents:UIControlEventTouchUpInside];
    CGFloat playBtnX = titleLabelX;
    CGFloat playBtnY = CGRectGetMaxY(describeLabel.frame) + 0.2 * LXMovieShowViewControllerMargin;
    CGFloat playBtnW = 150;
    CGFloat playBtnH = 30;
    playBtn.frame = CGRectMake(playBtnX, playBtnY, playBtnW, playBtnH);
    [topView addSubview:playBtn];
    
    UILabel *detailLabel = [[UILabel alloc]init];
    self.detailLabel = detailLabel;
    self.detailLabel.text = self.video._description;
    detailLabel.font = [UIFont systemFontOfSize:13];
    detailLabel.numberOfLines = 0;
    CGFloat detailLabelX = imageViewX;
    CGFloat detailLabelY = CGRectGetMaxY(imageView.frame) + LXMovieShowViewControllerMargin;
    CGFloat detailLabelW = topViewW - 2 * LXMovieShowViewControllerMargin;
    //计算本文高度
    CGSize detailLabelSize = [detailLabel.text boundingRectWithSize:CGSizeMake(detailLabelW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:detailLabel.font} context:nil].size;
    CGFloat detailLabelH = detailLabelSize.height;
    detailLabel.frame = CGRectMake(detailLabelX, detailLabelY, detailLabelW, detailLabelH);
    
    [topView addSubview:detailLabel];
    
}

#pragma mark 初始化initTabView
- (void)initBottomView
{
    UIView *bottomView = [[UIView alloc]init];
    CGFloat bottomViewX = 0;
    CGFloat bottomViewY = CGRectGetMaxY(self.topView.frame) - LXMovieShowViewControllerHideHeight;
    CGFloat bottomViewW = self.view.frame.size.width;
    CGFloat bottomViewH = self.view.frame.size.height - self.topView.frame.size.height - 20;
    bottomView.frame = CGRectMake(bottomViewX, bottomViewY, bottomViewW, bottomViewH);
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    //切换按钮视图
    UIView *tabView = [[UIView alloc]init];
    tabView.backgroundColor = [UIColor whiteColor];
    CGFloat tabViewX = 0;
    CGFloat tabViewY = 0;
    CGFloat tabViewW = bottomViewW;
    CGFloat tabViewH = 50;
    tabView.frame = CGRectMake(tabViewX, tabViewY, tabViewW, tabViewH);
    [bottomView addSubview:tabView];
    
    //添加切换按钮
    NSArray *tabTitleArr = @[@"推荐",@"评论"];
    for (int i=0; i<2; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:LXColor(41, 188, 208) forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(tabClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:tabTitleArr[i] forState:UIControlStateNormal];
        btn.tag = i;
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        CGFloat btnW = tabViewW / tabTitleArr.count;
        CGFloat btnX = i * btnW;
        CGFloat btnY = 0;
        CGFloat btnH = tabViewH;
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        [tabView addSubview:btn];
        [self.tabBtnArr addObject:btn];
        if (i == 0) {
            [self tabClick:btn];
        }
    }
    
    //添加滚动指示器
    UIScrollView *sliderView = [[UIScrollView alloc]init];
    sliderView.frame = CGRectMake(0, tabViewH - 3, tabViewW, 3);
    self.sliderView = sliderView;
    [tabView addSubview:sliderView];
    
    //添加红色指示器
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = LXColor(41, 188, 208);
    
    CGFloat viewW = 25;
    CGFloat viewH = sliderView.frame.size.height;
    CGFloat viewX = tabViewW / 4 ;
    CGFloat viewY = 0;
    view.frame = CGRectMake(viewX, viewY, viewW, viewH);
    
    CGPoint point = view.center;
    point.x = tabViewW / 4;
    view.center = point;
    
    [sliderView addSubview:view];
    
    //添加折叠按钮
    UIButton *hideBtn = [UIButton buttonWithType:UIButtonTypeContactAdd];
    hideBtn.tag = 0;
    [hideBtn addTarget:self action:@selector(hide:) forControlEvents:UIControlEventTouchUpInside];
    CGFloat hideBtnW = 30;
    CGFloat hideBtnH = 30;
    CGFloat hideBtnX = bottomViewW - hideBtnW;
    CGFloat hideBtnY = 0;
    hideBtn.frame = CGRectMake(hideBtnX, hideBtnY, hideBtnW, hideBtnH);
    [bottomView addSubview:hideBtn];
    
    //切换滚动视图
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.backgroundColor = MainBackgroundColor;
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    CGFloat scrollViewX = 0;
    CGFloat scrollViewY = tabViewH;
    CGFloat scrollViewW = tabViewW;
    CGFloat scrollViewH = bottomViewH - tabViewH;
    scrollView.frame = CGRectMake(scrollViewX, scrollViewY, scrollViewW, scrollViewH);
    scrollView.contentSize = CGSizeMake(tabTitleArr.count * scrollViewW, scrollViewH);
    [bottomView addSubview:scrollView];
    self.scrollView = scrollView;
    
    //添加推荐视频信息
    UITableView *recommendVideoTableView = [[UITableView alloc]init];
    recommendVideoTableView.delegate = self;
    recommendVideoTableView.dataSource = self;
    recommendVideoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    recommendVideoTableView.backgroundColor = MainBackgroundColor;
    recommendVideoTableView.tag = 0;
    self.recommendVideoTableView = recommendVideoTableView;
    [scrollView addSubview:recommendVideoTableView];
    
    CGFloat recommendVideoTableViewX = scrollViewX;
    CGFloat recommendVideoTableViewY = 0;
    CGFloat recommendVideoTableViewW = scrollViewW;
    CGFloat recommendVideoTableViewH = scrollViewH;
    recommendVideoTableView.frame = CGRectMake(recommendVideoTableViewX, recommendVideoTableViewY, recommendVideoTableViewW, recommendVideoTableViewH);
    
    //评论
    UITableView *commentsTableView = [[UITableView alloc]init];
    commentsTableView.backgroundColor = MainBackgroundColor;
    commentsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    commentsTableView.tag = 1;
    [scrollView addSubview:commentsTableView];
    
    CGFloat commentsTableViewX = recommendVideoTableViewW;
    CGFloat commentsTableViewY = 0;
    CGFloat commentsTableViewW = scrollViewW;
    CGFloat commentsTableViewH = scrollViewH;
    commentsTableView.frame = CGRectMake(commentsTableViewX, commentsTableViewY, commentsTableViewW, commentsTableViewH);
    
    //暂未开放
    UILabel *label = [[UILabel alloc]init];
    label.text = @"评论功能暂未开放";
    label.textAlignment = NSTextAlignmentCenter;
    CGFloat labelW = 200;
    CGFloat labelH = 70;
    CGFloat labelX = (commentsTableViewW - labelW) / 2;
    CGFloat labelY = 100;
    label.frame = CGRectMake(labelX, labelY, labelW, labelH);
    [commentsTableView addSubview:label];
}

/**
 *  隐藏或展现顶部内容
 */
- (void)hide:(UIButton *)btn
{
    CGRect bottomViewFrame = self.bottomView.frame;
    if (btn.tag == 0) {
        btn.tag = 1;
        bottomViewFrame.origin.y += LXMovieShowViewControllerHideHeight;
    }else{
        btn.tag = 0;
        bottomViewFrame.origin.y -= LXMovieShowViewControllerHideHeight;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        self.bottomView.frame = bottomViewFrame;
    }];
}

#pragma mark 选项卡切换变化视图
- (void)tabClick:(UIButton *)btn
{
    if (btn.selected == YES) {
        return;
    }
    self.currentBtn.selected = NO;
    btn.selected = YES;
    self.currentBtn = btn;
    
    [self.scrollView setContentOffset:CGPointMake(btn.tag * self.scrollView.frame.size.width, 0) animated:YES];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:self.scrollView.class]) {
        int num = self.scrollView.contentOffset.x / self.view.frame.size.width;
        if (self.currentBtn.tag != num) {
            [self tabClick:self.tabBtnArr[num]];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:self.scrollView.class]) {
        CGPoint point = self.scrollView.contentOffset;
        point.x = -point.x / 2;
        self.sliderView.contentOffset = point;
    }
    
    /*** tableview顶部不悬停 */
    CGFloat sectionHeaderHeight = LXVideoShowViewControllerTableViewHeaderHeight;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight){
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


#pragma mark - 获取推荐视频信息
- (void)getRecommendVideos
{
    //获取数据
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    NSString *url = @"http://cat666.com/cat666-interface/index.php/index/getCatRecommend";

    [mgr POST:url parameters:@{@"id":self.video.fid} success:^(AFHTTPRequestOperation *operation, id response) {
        NSArray *videos = response;
        NSMutableArray *videoArr = [NSMutableArray array];
        for (NSDictionary *dict in videos) {
            LXVideo *video = [LXVideo initWithDict:dict];
            [videoArr addObject:video];
        }
        self.videoArr = videoArr;

        [self getMarkVideos]; //获取收藏列表
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        [MBProgressHUD showError:@"您的网络开小差了..."];
    }];
}

#pragma mark - 获取收藏的视频信息
- (void)getMarkVideos
{
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    if (userName == nil) {
        [self.recommendVideoTableView reloadData];
    }else{
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"userId"] != nil) {
            AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
            NSString *url = @"http://cat666.com/cat666-interface/index.php/index/getCollection";
            [mgr POST:url parameters:@{@"userid":[[NSUserDefaults standardUserDefaults]objectForKey:@"userId"]} success:^(AFHTTPRequestOperation *operation, id response) {
                NSArray *arr = response;
                NSMutableArray *videoArr = [NSMutableArray array];
                if ([response isKindOfClass:[NSArray class]]) {
                    for (NSDictionary *dict in arr) {
                        LXVideo *video = [LXVideo initWithDict:dict];
                        [videoArr addObject:video];
                    }
                    self.markVideoArr = videoArr;
                }else{
                    self.markVideoArr = videoArr;
                }
                [self.recommendVideoTableView reloadData];
            } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
                [MBProgressHUD showError:@"您的网络开小差了..."];
            }];
        }
    }
}


//创建历史视频缓存表
//CREATE TABLE IF NOT EXISTS history (
//                                    id integer PRIMARY KEY AUTOINCREMENT,
//                                    videoUrl text NOT NULL,
//                                    videoName text NOT NULL,
//                                    videoImage text NOT NULL,
//                                    videoDate text NOT NULL
//                                    );
#pragma mark - 视频播放
- (void)moviePlay
{
//    NSDate *date = [NSDate date];
//    NSDateFormatter *dateForMatter = [[NSDateFormatter alloc]init];
//    [dateForMatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//    NSString *localTime = [dateForMatter stringFromDate:date];
//    NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_students (videoUrl,videoName,videoImage,videoDate) VALUES ('%@','%@','%@''%@');",self.video.videourl,self.video.fname,self.video.thumb,localTime];
//    [Sqlite runWithSql:sql];
    
    MoviePlayerViewController *vc = [[MoviePlayerViewController alloc]init];
    vc.video = self.video;
    
    [self.navigationController presentViewController:vc animated:YES completion:nil];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *time = [formatter stringFromDate:date];

    NSDictionary *historyDict = @{@"videoName":self.video.fname, @"videoThumb":self.video.thumb, @"videoId":@(self.video.ID), @"videoTime":time};
    
    //移除相同的历史记录
    for (int i=0; i<self.historyVideoArr.count; i++) {
        NSDictionary *dict = self.historyVideoArr[i];
        if (dict[@"videoId"] == historyDict[@"videoId"]) {
            [self.historyVideoArr removeObjectAtIndex:i];
        }
    }
    
    //添加历史记录
    if (self.historyVideoArr.count >= 20) {
        [self.historyVideoArr removeLastObject]; //移除最后一个记录
    }
    [self.historyVideoArr insertObject:historyDict atIndex:0];
    
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *file = [docPath stringByAppendingPathComponent:@"history.plist"];
    [self.historyVideoArr writeToFile:file atomically:YES];
}



#pragma mark - tableView的代理方法和数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videoArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return LXVideoShowViewControllerTableViewHeaderHeight;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *videoToolBar = [[UIView alloc]init];
    videoToolBar.frame = CGRectMake(0, 0, tableView.frame.size.width, LXVideoShowViewControllerTableViewHeaderHeight);
    videoToolBar.backgroundColor = MainBackgroundColor;
    

    NSArray *titleArr = @[@"分享",@"喂猫粮",@"收藏",@"缓存"];
    for (LXVideo *video in self.markVideoArr) { //判断是否收藏过
        if (video.ID == self.video.ID) {
            titleArr = @[@"分享",@"喂猫粮",@"已收藏",@"缓存"];
        }
    }
    
    NSArray *imageArr = @[@"share",@"catfood",@"star",@"link"];
    CGFloat btnH = 70;
    CGFloat btnW = btnH * LXImageOnTopButtonBili;
    CGFloat margin = (videoToolBar.frame.size.width - 30 * 2 - btnW * titleArr.count) / (titleArr.count - 1);
    for (int i=0; i<titleArr.count; i++) {
        CGFloat btnX = 30 + (margin + btnW) * i;
        
        //添加提示数字
        UILabel *label = [[UILabel alloc]init];
        [videoToolBar addSubview:label];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:13];
        label.layer.borderColor = [UIColor whiteColor].CGColor;
        if (i == 1) {
            label.text = [NSString stringWithFormat:@"%ld",self.video.catfood];
            self.catFoodLabel = label;
        }
        if (i == 2) {
            label.text = [NSString stringWithFormat:@"%ld",self.video.mark];
            self.markLabel = label;
        }
        
        CGFloat labelY = 5;
        CGFloat labelH = 18;
        label.frame = CGRectMake(btnX, labelY, btnW, labelH);
        
        LXImageOnTopButton *btn = [[LXImageOnTopButton alloc]init];
        [btn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(VideoToolBarBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = [UIFont systemFontOfSize:13];
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        btn.tag = i;
        btn.frame = CGRectMake(btnX, labelY + label.frame.size.height, btnW, btnH);
        [videoToolBar addSubview:btn];
        
        if (i == 2) {
            self.markButton = btn;
        }
    }
    
    /** 关注的用户 */
    LXConcernUserInfoCell *concernUserCell = [[LXConcernUserInfoCell alloc]init];
    concernUserCell.user = self.user;
    concernUserCell.MyDelegate = self;
    [videoToolBar addSubview:concernUserCell];
    
    concernUserCell.title = @"关注";
    for (LXUser *user in self.userArr) {
        if (user.ID == self.user.ID) {
            concernUserCell.title = @"已关注";
        }
    }
    
    
    CGFloat concernUserCellX = 10;
    CGFloat concernUserCellY = 100;
    CGFloat concernUserCellW = videoToolBar.frame.size.width - concernUserCellX * 2;
    CGFloat concernUserCellH = 70;
    concernUserCell.frame = CGRectMake(concernUserCellX, concernUserCellY, concernUserCellW, concernUserCellH);
    
    /** 分割线 */
    UIView *divider = [[UIView alloc]init];
    divider.backgroundColor = [UIColor grayColor];
    divider.alpha = 0.2;
    [videoToolBar addSubview:divider];
    
    CGFloat dividerH = 1;
    CGFloat dividerX = 10;
    CGFloat dividerY = LXVideoShowViewControllerTableViewHeaderHeight - dividerH;
    CGFloat dividerW = tableView.frame.size.width - dividerX * 2;
    divider.frame = CGRectMake(dividerX, dividerY, dividerW, dividerH);
    return videoToolBar;
}

- (void)VideoToolBarBtnClick:(UIButton *)btn
{
    switch (btn.tag) {
        case 0:
            [self share];
            break;
        case 1:
            [self catfood];
            break;
        case 2:
            [self mark:btn.titleLabel.text];
            break;
        case 3:
            [self download];
            break;
        default:
            break;
    }

}

#pragma mark - 分享
- (void)share
{
    [MBProgressHUD showError:@"暂未开放该功能"];
}
#pragma mark - 喂猫粮
- (void)catfood
{
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    if (userName == nil) {
        [MBProgressHUD showError:@"请先登录"];
        LXLoginViewController *login = [[LXLoginViewController alloc]init];
        [self.navigationController pushViewController:login animated:YES];
    }else{
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
        NSString *url = @"http://cat666.com/cat666-interface/index.php/index/catFood";
        
        [mgr POST:url parameters:@{@"userid":[[NSUserDefaults standardUserDefaults]objectForKey:@"userId"],@"videoid":@(self.video.ID), @"cat":@(1)} success:^(AFHTTPRequestOperation *operation, id response) {
            NSDictionary *dict = response;
            if ([dict.allKeys containsObject:@"you don't have enough cat food"]) {
                [MBProgressHUD showError:@"您的猫粮不足，请充值"];
            }else if ([dict.allKeys containsObject:@"failed"]){
                [MBProgressHUD showError:@"投喂猫粮失败"];
            }else if ([dict.allKeys containsObject:@"successed"]){
                [MBProgressHUD showSuccess:@"猫粮+1"];
                
                self.video.catfood += 1;
                self.catFoodLabel.text = [NSString stringWithFormat:@"%ld",self.video.catfood];
            }
        } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
            [MBProgressHUD showError:@"您的网络开小差了..."];
        }];
    }
}

#pragma mark - 点击收藏
- (void)mark:(NSString *)title
{
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    if (userName == nil) {
        [MBProgressHUD showError:@"请先登录"];
        LXLoginViewController *login = [[LXLoginViewController alloc]init];
        [self.navigationController pushViewController:login animated:YES];
    }else{
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
        if ([title isEqualToString:@"收藏"]) { // 收藏
            NSString * url = @"http://cat666.com/cat666-interface/index.php/index/setCollection";
            [mgr POST:url parameters:@{@"userid":[[NSUserDefaults standardUserDefaults]objectForKey:@"userId"], @"videoid":@(self.video.ID)} success:^(AFHTTPRequestOperation *operation, id response) {
                NSDictionary *dict = response;
                if ([dict.allKeys containsObject:@"successed"]) {
                    [MBProgressHUD showSuccess:@"收藏成功"];
                    [self.markButton setTitle:@"已收藏" forState:UIControlStateNormal];
                    self.video.mark += 1;
                    self.markLabel.text = [NSString stringWithFormat:@"%ld",self.video.mark];
                }else{
                    [MBProgressHUD showSuccess:@"收藏失败"];
                }
            } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
                [MBProgressHUD showError:@"您的网络开小差了..."];
            }];
        }
        
        if ([title isEqualToString:@"已收藏"]) { // 取消收藏
            NSString * url = @"http://cat666.com/cat666-interface/index.php/index/cancelCollection";
            [mgr POST:url parameters:@{@"userid":[[NSUserDefaults standardUserDefaults]objectForKey:@"userId"], @"videoid":@(self.video.ID)} success:^(AFHTTPRequestOperation *operation, id response) {
                NSDictionary *dict = response;
                if ([dict.allKeys containsObject:@"successed"]) {
                    [MBProgressHUD showSuccess:@"取消收藏成功"];
                    [self.markButton setTitle:@"收藏" forState:UIControlStateNormal];
                    self.video.mark -= 1;
                    self.markLabel.text = [NSString stringWithFormat:@"%ld",self.video.mark];
                }else{
                    [MBProgressHUD showSuccess:@"取消收藏成功"];
                }
            } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
                [MBProgressHUD showError:@"您的网络开小差了..."];
            }];
        }
    }
    
}

#pragma mark - 下载
- (void)download
{
    //判断是否有别的视频正在下载
    NSString *downloadLock = [[NSUserDefaults standardUserDefaults]valueForKey:@"downloadLock"];
    if (downloadLock == nil) { //无别的视频正在缓存
        [[NSUserDefaults standardUserDefaults]setValue:@"yes" forKey:@"downloadLock"];
        
        //写入plist文件
        NSString *videoPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSMutableDictionary *videoDict = [NSMutableDictionary dictionaryWithDictionary:@{@"videoName":self.video.fname, @"videoPicture":self.video.fname, @"videoProgress":@"0"}];
        
        //判断是否下载过
        for (int i=0;i<self.videoDownLoad.count;i++) {
            NSDictionary *dict = self.videoDownLoad[i];
            if ([dict[@"videoName"] isEqualToString:self.video.fname]) {
                if ([dict[@"videoProgress"] isEqualToString:@"1.000"]) { //下载完成
                    [MBProgressHUD showError:@"您已经缓存过该视频"];
                    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"downloadLock"];
                    return;
                }else{  //下载未完成,重新下载
                    [self.videoDownLoad removeObjectAtIndex:i];
                }
            }
        }
        [MBProgressHUD showSuccess:@"正在缓存..."];
        [self.videoDownLoad addObject:videoDict];
        [self.videoDownLoad writeToFile:self.filePath atomically:YES];
        
        [self downloadFileURL:self.video.thumb savePath:videoPath fileName:self.video.fname type:@"jpg" videoDict:nil]; //下载缩略图
        [self downloadFileURL:self.video.videourl savePath:videoPath fileName:self.video.fname type:@"mp4" videoDict:videoDict]; //下载视频
    }else{
        [MBProgressHUD showError:@"其他视频正在缓存..."];
    }
}


#pragma mark - 文件下载函数
/**
 *  下载文件
 *
 *  @param aUrl      文件链接地址
 *  @param aSavePath 文件保存路径
 *  @param aFileName 文件名称
 *  @param type      文件类型
 *  @param Videodict 文件字典模型
 */
- (void)downloadFileURL:(NSString *)aUrl savePath:(NSString *)aSavePath fileName:(NSString *)aFileName type:(NSString *)type videoDict:(NSDictionary *)videoDict
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //文件目录
    NSString *fileName = [NSString stringWithFormat:@"%@/%@.%@", aSavePath, aFileName,type];
    
    //创建附件存储目录
    if (![fileManager fileExistsAtPath:aSavePath]) {
        [fileManager createDirectoryAtPath:aSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
        
    //下载附件
    NSURL *url = [[NSURL alloc] initWithString:aUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    __block AFHTTPRequestOperation *weakOperation = operation;
    operation.inputStream   = [NSInputStream inputStreamWithURL:url];
    operation.outputStream  = [NSOutputStream outputStreamToFileAtPath:fileName append:NO];

    //下载进度控制
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        int num = (float)totalBytesRead/totalBytesExpectedToRead * 10000;
        if (num % 10 == 0) { //每下载1%就更新一次
            if (videoDict != nil) {
                [videoDict setValue:[NSString stringWithFormat:@"%.3f",(float)totalBytesRead/totalBytesExpectedToRead] forKey:@"videoProgress"];
                NSArray *videoArr  = [NSArray arrayWithContentsOfFile:self.filePath];
                BOOL iscancel = YES;
                for (NSDictionary *dict in videoArr) {
                    if ([dict[@"videoName"] isEqualToString:aFileName]) {
                        iscancel = NO;
                    }
                }
                if (iscancel) {
                    [weakOperation cancel];
                }else{
                    [self.videoDownLoad writeToFile:self.filePath atomically:YES];
                }
            }
        }
    }];
    
    //已完成下载
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (videoDict != nil) {
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"downloadLock"];
            [MBProgressHUD showSuccess:@"视频缓存完成"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"downloadLock"];
        if (videoDict != nil) {
            [MBProgressHUD showSuccess:@"视频缓存失败"];
        }
    }];
        
    [operation start];

}


- (LXSearchTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"Cell";
    
    LXSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    cell.backgroundColor = MainBackgroundColor;
    if (cell == nil) {
        cell = [[LXSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    
    cell.video = self.videoArr[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LXVideoShowViewController *movieShowVc = [[LXVideoShowViewController alloc]init];
    movieShowVc.video = self.videoArr[indexPath.row];
    [self.navigationController pushViewController:movieShowVc animated:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//#pragma mark - 控制器销毁
//- (void)dealloc
//{
//    [self.video removeObserver:self forKeyPath:@"viewcounts"];
//}

#pragma mark - 关注cell代理
- (BOOL)concernUserInfoCell:(LXConcernUserInfoCell *)concernUserInfoCell title:(NSString *)title
{
    NSString *userName = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
    if (userName == nil) {
        LXLoginViewController *loginVc = [[LXLoginViewController alloc]init];
        [self.navigationController pushViewController:loginVc animated:YES];
        [MBProgressHUD showError:@"请先登录"];
        return NO;
    }
    //获取数据
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSNumber *followId = @(self.user.ID);
    
    if([title isEqualToString:@"关注"]){
        NSString *url = @"http://cat666.com/cat666-interface/index.php/index/setFollow";
        
        [mgr POST:url parameters:@{@"userid":userId, @"followid":followId} success:^(AFHTTPRequestOperation *operation, id response) {
            NSDictionary *dict = response;
            if([dict[@"successed"] integerValue] == 1){
                [MBProgressHUD showSuccess:@"关注成功"];
            }else{
                [MBProgressHUD showSuccess:@"关注失败"];
            }
        } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
            [MBProgressHUD showError:@"您的网络开小差了..."];
        }];
    }else{
        NSString *url = @"http://cat666.com/cat666-interface/index.php/index/cancelFollow";
        
        [mgr POST:url parameters:@{@"userid":userId, @"followid":followId} success:^(AFHTTPRequestOperation *operation, id response) {
            NSDictionary *dict = response;

            if([dict[@"successed"] integerValue] == 1){
                [MBProgressHUD showSuccess:@"取消关注成功"];
            }else{
                [MBProgressHUD showSuccess:@"取消关注失败"];
            }
        } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
            [MBProgressHUD showError:@"您的网络开小差了..."];
        }];
    }
    return YES;
}

@end
